package cn.internship.modules.manage.controller;

import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

import cn.internship.common.exception.RRException;
import cn.internship.modules.manage.entity.StudentInfoEntity;
import cn.internship.modules.manage.entity.dto.ReportInsertDTO;
import cn.internship.modules.manage.entity.dto.ReportSearch;
import cn.internship.modules.manage.entity.dto.WeeklyRecordSearch;
import cn.internship.modules.manage.service.StudentInfoService;
import cn.internship.modules.oss.cloud.OSSFactory;
import cn.internship.modules.oss.entity.SysOssEntity;
import cn.internship.modules.sys.controller.AbstractController;
import cn.internship.modules.sys.entity.SysUserRoleEntity;
import cn.internship.modules.sys.service.SysUserRoleService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import cn.internship.modules.manage.entity.InternshipReportEntity;
import cn.internship.modules.manage.service.InternshipReportService;
import cn.internship.common.utils.PageUtils;
import cn.internship.common.utils.R;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 
 *
 * @author haha
 * @email haha@gmail.com
 * @date 2023-02-20 15:58:08
 */
@RestController
@RequestMapping("manage/internshipreport")
@Slf4j
public class InternshipReportController extends AbstractController {
    @Autowired
    private InternshipReportService internshipReportService;

    @Resource
    private StudentInfoService studentInfoService;

    @Resource
    private SysUserRoleService sysUserRoleService;

    @Value("${file.base.url}")
    private String baseUrl;

//    /**
//     * 列表
//     */
//    @RequestMapping("/list")
//    @RequiresPermissions("manage:internshipreport:list")
//    public R list(@RequestParam Map<String, Object> params){
//        PageUtils page = internshipReportService.queryPage(params);
//
//        return R.ok().put("page", page);
//    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("manage:internshipreport:list")
    public R list(ReportSearch search){
        //获取用户ID
        Long userId = getUserId();
        //通过用户ID查询角色
        LambdaQueryWrapper<SysUserRoleEntity> queryWrap = new LambdaQueryWrapper<>();
        queryWrap.eq(SysUserRoleEntity::getUserId,userId);
        SysUserRoleEntity one = sysUserRoleService.getOne(queryWrap);
        if (one == null){
            return R.error("该用户不属于任何角色");
        }
        if (one.getRoleId() == 2){
            search.setTeaUserId(userId);
        }
        if (one.getRoleId() == 3){
            search.setStuUserId(userId);
        }
        PageUtils page = internshipReportService.listByPage(search);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("manage:internshipreport:info")
    public R info(@PathVariable("id") Long id){
		InternshipReportEntity internshipReport = internshipReportService.getById(id);

        return R.ok().put("internshipReport", internshipReport);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("manage:internshipreport:save")
    @Transactional(rollbackFor = Exception.class)
    public R save(@RequestBody ReportInsertDTO reportInsertDTO) throws IOException {
        InternshipReportEntity internshipReport = new InternshipReportEntity();
        BeanUtils.copyProperties(reportInsertDTO,internshipReport);
        internshipReport.setCreateTime(new Date());
        Long userId = getUserId();
        //获取学生ID
        LambdaQueryWrapper<StudentInfoEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StudentInfoEntity::getUserId,userId);
        StudentInfoEntity studentInfo = studentInfoService.getOne(queryWrapper);
        internshipReport.setStuId(Long.parseLong(studentInfo.getId().toString()));
        //上传报告
//        File uploadFile = new File(baseUrl);
//        if (!uploadFile.exists()){
//            uploadFile.mkdirs();
//        }
//        String originalFilename = reportInsertDTO.getFile().getOriginalFilename();
//        String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
//        //重新随机生成名字
//        String filename = UUID.randomUUID()+suffixName;
//        String path = userId+"/"+filename;
//        File localFile = new File(baseUrl,path);
//        if (!localFile.exists()){
//            localFile.getParentFile().mkdirs();
//        }
//        try {
//            reportInsertDTO.getFile().transferTo(localFile);
//        }catch (IOException e){
//            e.printStackTrace();
//            log.error("上传文件失败");
//        }
        internshipReport.setReportUrl(reportInsertDTO.getReportUrl());
        internshipReport.setReportName(reportInsertDTO.getReportName());
		internshipReportService.save(internshipReport);

        return R.ok();
    }

    @PostMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }

        Long userId = getUserId();
        //上传文件
        String originalFilename = file.getOriginalFilename();
        String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
        //重新随机生成名字
        String filename = UUID.randomUUID()+suffixName;
        String path = userId+"/"+filename;
        File localFile = new File(baseUrl,path);
        if (!localFile.exists()){
            localFile.getParentFile().mkdirs();
        }
        try {
            file.transferTo(localFile);
        }catch (IOException e){
            e.printStackTrace();
            log.error("上传文件失败");
        }


        return R.ok().put("url", path);
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("manage:internshipreport:update")
    public R update(@RequestBody InternshipReportEntity internshipReport){
		internshipReportService.updateById(internshipReport);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("manage:internshipreport:delete")
    public R delete(@RequestBody Long[] ids){
		internshipReportService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }


    /**
     * 评分
     */
    @RequestMapping("/score")
    @RequiresPermissions("manage:internshipreport:score")
    public R score(@RequestBody InternshipReportEntity internshipReport){
        internshipReportService.updateById(internshipReport);

        return R.ok();
    }


    /**
     * 下载报告
     * @param id
     * @param response
     * @return
     */
    @RequestMapping("/downReport/{id}")
    @RequiresPermissions("manage:internshipreport:downReport")
    public void downReport(@PathVariable("id") Long id, HttpServletResponse response,HttpServletRequest request) throws UnsupportedEncodingException {
        InternshipReportEntity reportEntity = internshipReportService.getById(id);
        if (reportEntity == null){
            throw new RuntimeException("文件不存在");
        }
//        File file = new File(baseUrl,reportEntity.getReportUrl());
//        try {
//            FileInputStream inputStream = new FileInputStream(file);
//            byte[] buffer = new byte[inputStream.available()];
//            inputStream.read(buffer);
//            inputStream.close();
//            // 清空response
//            response.reset();
//            // 设置response的Header
//            response.setCharacterEncoding("UTF-8");
//            //Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
//            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(reportEntity.getReportName()+".pdf", "UTF-8"));
//            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
//            response.setContentType("application/octet-stream");
//            outputStream.write(buffer);
//            outputStream.flush();
//            outputStream.close();
//        }catch (Exception e){
//            if (log.isDebugEnabled()){
//                log.debug("下载文件失败...");
//            }
//            throw new RuntimeException("下载文件失败");
//        }
        if (reportEntity.getReportUrl() == null) {
            throw new RuntimeException("文件为空");
        }
        Path path = Paths.get(baseUrl, reportEntity.getReportUrl());
        if (!Files.exists(path)) {
            throw new RuntimeException("文件不存在");
        }
        File file = path.toFile();
        response.reset();
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setContentLength((int) path.toFile().length());
        response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(file.getName(), "UTF-8"));
        /*
         * 跨域配置
         * */
        response.addHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.addHeader("Access-Control-Allow-Credentials", "true");
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
        response.addHeader("Access-Control-Allow-Headers", "Content-Type");

        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));) {
            byte[] buffer = new byte[1024];
            ServletOutputStream outputStream = response.getOutputStream();
            int i;
            while ((i = bis.read(buffer)) != -1) {
                outputStream.write(buffer, 0, i);
                outputStream.flush();
            }
        } catch (Exception e) {
            throw new RuntimeException("文件下载超限");
        }
    }

    /**
     * 文件预览功能
     * @param id 文件路径
     * @param response 输出
     */
    @GetMapping("fileView/{id}")
    public void fileView(@PathVariable("id") Integer id, HttpServletResponse response){
        InternshipReportEntity reportEntity = internshipReportService.getById(id);
        if (reportEntity == null){
            throw new RuntimeException("文件不存在");
        }
        File file = new File(baseUrl,reportEntity.getReportUrl());
        if (file.exists()){
            byte[] data = null;
            try {
                FileInputStream input = new FileInputStream(file);
                data = new byte[input.available()];
                input.read(data);
                response.getOutputStream().write(data);
                input.close();
            } catch (Exception e) {
                if (log.isDebugEnabled()){
                    log.debug("文件显示发生异常..{}",e.getMessage());
                }
            }
        }else{
            return;
        }
    }



}
